<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\MallGoods;
use App\Model\MallGoodsSku;
use App\Model\Number;
use App\Model\OperationLogs;
use App\Model\SendGoodsRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use mysql_xdevapi\Exception;

class SendGoodsRecordController extends BaseController
{
    protected $model;
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->model = new SendGoodsRecord();
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->model->getList($request));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, MallGoods $mallGoods, Number $number, MallGoodsSku $mallGoodsSku)
    {
        set_time_limit(0);
        try{
            $validator = Validator::make($request->all(),[
                'goods_id' => 'bail|required|exists:api.mall_goods|integer',
                'sku_id' => 'bail|required|exists:api.mall_goods_sku|integer',
                'user_id' => 'bail|required',
//                'uuid' => 'bail|required|string',
//                'type' => 'bail|required|integer',Rule::in(1,2,3,4,5,6)
            ],[
                'goods_id.required' => '商品不可为空',
                'goods_id.exists' => '商品不存在',
                'sku_id.required' => '商品SKU不可为空',
                'sku_id.exists' => '商品SKU不存在',
                'user_id.required' => '用户不可为空',
//                'user_id.exists' => '用户不存在',
//                'type.required' => '商品类型不可为空',
            ]);
            write_log('sendGoods','sendGoods store Request' ,json_encode($request->all(),JSON_UNESCAPED_UNICODE));
            if($validator->fails()){
                return $this->toJson(self::PARAM_ERROR, [],$validator->errors()->all()[0]);
            }

            $fillData = [];
	    $good = $mallGoods->getGoodByGoodId($request->input('goods_id'));

	    if ($good['is_show'] != 1) {
                return $this->toJson(self::ERROR,[], '装扮需设置显示才能赠送');
            }


            $fillData['goods_name'] = $good['goods_name'];

            $goodsSku = $mallGoodsSku->getSkuBySkuId($request->input('sku_id'));
            $fillData['sku_desc'] = "{$goodsSku['time_limit']}天 {$goodsSku['price']}钻石";

            $url = getKkaudioApiUrl();
            $res = curl_request($url.'/inner/mall/back_send_goods',[
                'user_id' => 11,
                'to_user_id' => $request->input('user_id'),
                'goods_id' => $request->input('goods_id'),
                'goods_name' => $good['goods_name'],
                'goods_type' => $good['goods_type'],
                'sku_id' => $goodsSku['sku_id'],
                'time_limit' => $goodsSku['time_limit'],
                'price' => $goodsSku['price'],
                'act_type' => 0
            ],'json','POST');
            write_log('sendGoods','sendGoods store response' ,json_encode($res,JSON_UNESCAPED_UNICODE));
            if($res['code'] == 0){
                $user_ids = explode(',',$request->input(['user_id']));
                $number = $number->getNicknameByUserIds($user_ids);
                $sendGoodsRecord = [];
                foreach ($number as $n){
                    try {
                        $request['user_id'] = $n['user_id'];
                        $request['uuid'] = $n['UUID'];
                        $fillData['nickname'] = $n['nickname'];
                        $sendGoodsRecord = $this->model->createData($request, $fillData);
                        Artisan::call('send:custom:msg', [
                            'type' => 0,
                            'all' => 0,
                            'msg' => $request->input('sys_notice'),
                            'user' => $n['UUID']
                        ]);
                        OperationLogs::createData($request, OperationLogs::SEND_GOODS_RECORD, '赠送礼物', $good['goods_name']);
                    }catch (\Exception $exception){
                        write_log('sendGoods','sendGoods sendMsg' ,$exception->getMessage());
                    }
                }
                return $this->toJson(self::SUCCESS, $sendGoodsRecord);
            }
        }catch (\Exception $e){
            write_log('sendGoods','sendGoods Error' ,$e->getMessage());
            return $this->toJson(self::ERROR,[], $e->getMessage().$e->getLine());
        }
    }
}
